package com.songcha.library_business.proxy.database

import com.songcha.library_business.proxy.userinfo.UserInfoManager
import com.songcha.library_common.util.LogUtil
import com.songcha.library_common.util.TimeUtil
import com.songcha.library_database_douyue.bean.BookBrowseHistoryBean
import com.songcha.library_database_douyue.greendao.BookBrowseHistoryBeanDao
import com.songcha.library_database_douyue.manager.GreenDaoManager

class BookBrowseHistoryDaoManager {
    companion object{
        const val MAX_HISTORY_SIZE=30
        @JvmStatic
        fun addBrowseHistory(bookId:String){
            try{
                val dao=GreenDaoManager.getInstance().bookBrowseHistoryDao
                val bean=BookBrowseHistoryBean()
                bean.apply {
                    this.bookId=bookId
                    userId= UserInfoManager.userId
                    time=TimeUtil.getCurrentTimeSecond()
                }
                //clear all if count>max size
                val deleteQB=dao.queryBuilder()
                deleteQB.where(BookBrowseHistoryBeanDao.Properties.UserId.eq(UserInfoManager.userId))
                if(deleteQB.list().size>=MAX_HISTORY_SIZE){
                    deleteQB.buildDelete().executeDeleteWithoutDetachingEntities()
                }

                //if bookid and userid is unique，insert ,otherwise do noting
                val insertQB=dao.queryBuilder()
                insertQB.where(BookBrowseHistoryBeanDao.Properties.BookId.eq(bookId))
                    .where(BookBrowseHistoryBeanDao.Properties.UserId.eq(UserInfoManager.userId))
                val list=insertQB.list()
                if(list.size==0){
                    dao.insert(bean)
                }else{
                    val bean=list[0]
                    bean.time=TimeUtil.getCurrentTimeSecond()
                    dao.update(bean)
                }
            }catch (e:Exception){
                LogUtil.log("保存浏览失败异常")
                e.printStackTrace()
            }

        }

        @JvmStatic
        fun getBrowseHistoryList():MutableList<BookBrowseHistoryBean>{
            val dao=GreenDaoManager.getInstance().bookBrowseHistoryDao
            val qb=dao.queryBuilder()
            qb.where(BookBrowseHistoryBeanDao.Properties.UserId.eq(UserInfoManager.userId))
                .orderDesc(BookBrowseHistoryBeanDao.Properties.Time)
            return qb.list()
        }



    }
}